<template>
	<view class="restaurant-add-dishes-container">
		<common-title :title="titleContent" @clickLeft="backToUpPage" @clickRight="clearaddDishInfo"></common-title>
		<!-- 新增菜品表单 -->
		<view>
			<uni-forms class="restaurant-add-dishes-form" ref="addDishesForm" :modelValue="addDishesFormData" :rules="addDishesFromRules">
				<!-- 菜名：dishName -->
				<uni-forms-item label="菜名" required name="dishName">
					<uni-easyinput v-model="addDishesFormData.dishName" placeholder="请输入菜名"></uni-easyinput>
				</uni-forms-item>
				<!-- 定价：price -->
				<uni-forms-item label="定价" required name="price">
					<uni-easyinput v-model="addDishesFormData.price" placeholder="请输入定价"></uni-easyinput>
				</uni-forms-item>
				<!-- 菜品图片：dishImage -->
				<uni-forms-item label="菜品图片" required name="dishImage">
					<uni-file-picker :limit="1" file-mediatype="image" 
									 :sizeType="['compressed']" @select="imageUploadSelect" 
									 @delete="imageUploadDelete"
									 @success="imageUploadSuccess" title="(画幅4:3)"
									 :auto-upload="true" disable-preview 
									 v-model="dishImgeFile"/>
				</uni-forms-item>
				<!-- 描述：description -->
				<uni-forms-item label="菜品描述" name="description">
					<uni-easyinput trim type="textarea" v-model="addDishesFormData.description" placeholder="请输入菜品描述(30字以内)"/>
				</uni-forms-item>
				<!-- 是否上架：status -->
				<uni-forms-item label="状态" name="staus" required>
					<uni-data-checkbox v-model="addDishesFormData.status" :localdata="dishesStatus"></uni-data-checkbox>
				</uni-forms-item>
				
				<!-- 菜品类别：categoryId -->
				<uni-forms-item label="菜品类别" name="categoryId" required>
					<uni-data-select
					      v-model="addDishesFormData.categoryId"
					      :localdata="categoryId"
					/>
				</uni-forms-item>
				
			</uni-forms>
			<!-- 底部操纵按钮 -->
			<view class="buttonOption">
			    <view 
			        class="tempSaveDishButton" 
			        @click="tempSave" 
			        :class="{'active': isPressedTemp}" 
			        @touchstart="onPressTemp" 
			        @touchend="onReleaseTemp">
			        保存草稿
			    </view>
			    <view 
			        class="addDishButton" 
			        @click="submit" 
			        :class="{'active': isPressedSub}" 
			        @touchstart="onPressSub" 
			        @touchend="onReleaseSub">
			        新增菜品
			    </view>
			</view>
		</view>
	</view>
</template>

<script setup>
	
	import { ref, onMounted  } from 'vue';
	
	import { apiGetRestaurantAllCategories, apiPostRestaurantDish } from '@/utils/apiRestaurant.js';
	import { apiUploadFile } from '@/utils/apiFiles.js';
	
	import { setDataToStorageTest, getDataFromStorage } from '@/utils/commonUtils';
	
	//标题内容
	const titleContent = ref({
		left:'返回',
		midst:'餐厅-新增菜品',
		right: '清空'
	});
	//返回
	const backToUpPage = () => {
		uni.switchTab({
			url:'/pages/manage/manage'
		});
	};
	//清空新增菜品数据
	const clearaddDishInfo = () => {
		uni.removeStorage({
			key:'tempSaveDish'
		});
		addDishesFormData.value = { ...initialFormData };
		dishImgeFile.value = [];
	};
	
	const dishImgeFile = ref([]);
	
	
	// 表单数据
	// 定义初始状态
	const initialFormData = {
	    dishName: '',
	    price: '',
	    dishImage: null,
	    description: '',
	    status: 1,
	    categoryId: null
	};
	
	// 创建 ref 对象
	const addDishesFormData = ref({ ...initialFormData });
	
	//菜品状态
	const dishesStatus = ref([
		{text: '上架',value: 1}, 
		{text: '下架',value: 0}
	]);
	//TODO:菜品类别
	
	const categoryId = ref([]);
	
	const getAllCategories = async () => {
		try{
			let res = await apiGetRestaurantAllCategories();
			categoryId.value = res.map(item => ({
				text: item.categoryName,
				value: item.id
			}));
		}catch(e){
			//TODO handle the exception
		}
	};
	getAllCategories();
	
	
	// 表单引用
	const addDishesForm = ref(null);
	
	
	// 表单验证规则
	const addDishesFromRules = {
		dishName: {
			rules: [
				{
					required: true,
					errorMessage: '菜名不能为空'
				},
				{
					minLength: 1,
					maxLength: 10,
					errorMessage: '菜名长度在 {minLength} 到 {maxLength} 个字符',
					validateFunction(rule, value, data, callback) {
						// 正则表达式定义为字符串
						const pricePattern = new RegExp('^(?=[^_])[\\u4e00-\\u9fa5A-Za-z0-9_]+$');
						
						if (!pricePattern.test(value)) {
							callback('只能是中文，字母，数字，下划线，且不能下划线开头');
						} else {
							callback(); // 校验通过
						}
					}
				}
			]
		},
		price: {
			rules: [
				{
					required: true,
					errorMessage: '价格不能为空'
				},
				{
					validateFunction(rule, value, data, callback) {
						// 正则表达式定义为字符串
						const pricePattern = new RegExp('^(0|[1-9]\\d*)(\\.\\d{1,2})?$');
	
						if (!pricePattern.test(value)) {
							callback('价格格式不正确，最多为两个小数位的金额');
						} else {
							callback(); // 校验通过
						}
					}
				}
			]
		},
		dishImage: {
			rules: [
				{
					required: true,
					errorMessage: '图片不能为空'
				}
			]
		},
		description: {
			rules: [
				{
					minLength: 0,
					maxLength: 30,
					errorMessage: '描述长度在 {minLength} 到 {maxLength} 个字符',
				}
			]
		},
		status: {
			rules: [
				{
					required: true,
					errorMessage: '菜品状态不能为空'
				}
			]
		},
		categoryId: {
			rules: [
				{
					required: true,
					errorMessage: '请选择类别'
				}
			]
		}
	};
	
	// 在组件挂载时设置验证规则
	onMounted(() => {
		// console.log(addDishesForm.value)
	    addDishesForm.value.setRules(addDishesFromRules);
		// 异步获取数据
		getDataFromStorage('tempSaveDish')
		    .then(res => {
		        const { dishName = '', price = '', dishImage = '', description = '', status = 1, categoryId = null } = (res && typeof res === 'object') ? res : {};
		
		        // 更新 formData，使用解构赋值和默认值
		        addDishesFormData.value = {
		            dishName,
		            price,
		            description,
		            status,
		            categoryId
		        };
				// console.log(addDishesFormData.value);
		    })
		    .catch(error => {
				// console.log('1')
		    });
	});
	
	
	
	//TODO: 图片上传成功执行的方法
	const imageUploadSuccess = (e) => {
		console.log('上传成功',e);
	};
	//选择图片成功执行的方法
	const imageUploadSelect = (e) => {
		addDishesFormData.value.dishImage = e.tempFilePaths[0];
	};
	
	//移除图片
	const imageUploadDelete = (e) => {
		console.log(e)
		addDishesFormData.value.dishImage='';
	};
	
	
	//-----------------------------------------底部按钮-------------------------------------
	const isPressedTemp = ref(false);
	const isPressedSub = ref(false);
	
	// 提交表单
	let isSubmitting = false; // 标志变量，初始化为 false
	
	const submit = async () => {
	    if (isSubmitting) return; // 如果正在提交，则直接返回
	
	    isSubmitting = true; // 设置为正在提交状态
	
	    try {
	        // 等待表单验证的结果
	        await addDishesForm.value.validate();
			
			// 上传图片并获取返回的文件名
			let dishImageName = await apiUploadFile(addDishesFormData.value.dishImage);
			
			// 创建 FormData 实例
			const formData = new FormData();
	
			// 将表单数据添加到 FormData
			for (const key in addDishesFormData.value) {
				formData.append(key, addDishesFormData.value[key]);
			}
			
			// 将上传的图片名称加入到 FormData 中
			formData.set('dishImage', dishImageName);
	
			
	        let result = await apiPostRestaurantDish(formData); // 确保这里使用 await
	
	        // 检查状态码（根据你的 API 返回调整条件）
	        if (result === '200') { // 此处假设 result 是一个字符串
	            uni.showToast({
	                title: "新增菜品成功",
	                icon: 'success'
	            });
	        }
	
	        
	
	    } catch (err) {
	        console.log('表单错误信息：', err); // 捕获验证和 API 调用中的错误
	    } finally {
			// TODO: 提交后清除表单信息等操作
			clearaddDishInfo();
	        isSubmitting = false; // 重置提交状态
	    }
	};
	
	//保存草稿
	const tempSave = () => {
		setDataToStorageTest('tempSaveDish', addDishesFormData.value);
		uni.showToast({
			title:'保存草稿',
			icon:'success'
		})
	};
	
	//点击保存草稿按钮
	const onPressTemp = () => {
		isPressedTemp.value = true;
	};
	
	//长按草稿按钮
	const onReleaseTemp = () => {
		isPressedTemp.value = false;
	};
	
	//点击新增按钮
	const onPressSub = () => {
		isPressedSub.value = true;
	};
	
	//长按新增按钮
	const onReleaseSub = () => {
		isPressedSub.value = false;
	};
	
	
	
	
</script>

<style lang="scss" scoped>
	.restaurant-add-dishes-container{
		.restaurant-add-dishes-form{
			padding:30rpx;
		}
		.buttonOption{
			display: flex;
			align-items: center;
			justify-content: center;
			margin-top: 50rpx;
			font-weight: bold;
			font-size: 36rpx;
			color: #000000 ;
			padding: 30rpx;
			.tempSaveDishButton{
				margin-right: 20rpx;
				width: 200rpx;
				height: 120rpx;
				border-radius: 40rpx;
				display: flex;
				align-items: center;
				justify-content: center;
				background-color: #e4e4e4;
				box-shadow: 0 0 30rpx rgba(0, 0, 0, 0.05);
			}
			.addDishButton{
				margin-left: 20rpx;
				width: 400rpx;
				height: 120rpx;
				border-radius: 40rpx;
				display: flex;
				align-items: center;
				justify-content: center;
				background-color: $brand-theme-color;
				box-shadow: 0 0 30rpx rgba(0, 0, 0, 0.05);
			}
			.tempSaveDishButton.active,
			.addDishButton.active {
			    background-color: #e4e4e4; /* 按下时的背景色 */
			    color: #999; /* 按下时的文字颜色 */
			}
		}
	}
</style>